package test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Tang
 * @classname Server
 * @description [  ]
 * @date 2021/2/22 21:31
 */
public class Server {

    public static void main(String[] args) throws Exception {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",9000));

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()) {
                    System.out.println("客户端接收socket事件...");
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_WRITE);
                } else if (selectionKey.isConnectable()) {
                    System.out.println("客户端与服务端连接建立成功...");
                } else if (selectionKey.isWritable()) {
                    SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                    buffer.put("hello!".getBytes());
                    buffer.flip();
                    socketChannel.write(buffer);
                    selectionKey.interestOps(SelectionKey.OP_READ);
                    selector.wakeup();
                    System.out.println("写完成...");
                } else if (selectionKey.isReadable()) {
                    System.out.println("读事件触发...");
                    SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                    while (buffer.hasRemaining()) {
                        socketChannel.read(buffer);
                        buffer.flip();
                        System.out.println("接收到的msg:"+new String(buffer.array()));
                        System.out.println(buffer.position() + "--->" + buffer.limit());
                    }
                }
                iterator.remove();
            }
        }
    }
}